import axios from '@/utils/fetch'
import {
  getToken,
  removeToken
} from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    username: '',
    nickname: '',
    roles: '',
    roletype: null,
  },

  mutations: {

    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NICKNAME: (state, nickname) => {
      state.nickname = nickname
    },
    SET_USERNAME: (state, username) => {
      state.username = username
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_ROLETYPE: (state, roletype) => {
      state.roletype = roletype
    }
  },

  actions: {
    // 获取用户信息
    GetUserInfo({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        axios.post('/accounts/info').then(response => {
          const userinfo = response.data.data.user
          if (userinfo.roles == "ROLE_ADMIN") {
            commit('SET_ROLETYPE', 0)
            commit('SET_ROLES', "ADMIN")
          } else {
            commit('SET_ROLETYPE', 1)
            commit('SET_ROLES', "USER")
          }
          commit('SET_USERNAME', userinfo.username)
          commit('SET_NICKNAME', userinfo.nickname)
          resolve(userinfo)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({
      commit,
      state
    }) {
      return new Promise((resolve, reject) => {
        axios.post("/accounts/signout").then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', "")
          commit('SET_NICKNAME', '')
          commit('SET_USERNAME', "")
          commit('SET_ROLETYPE', null)
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default user